%% experiment session for cue-based expectation modulation

subject_string='S_'; %add subject number manually, check in table which number
filename=[subject_string ' ' datestr(now,'dd-mmmm-yyyy')];
disp(filename);
%% Init
% initialize VAS / NI
disp('Initializing')
NI=NI_initialize;
calibrateVAS=VAS_calibration(NI,10);    % VAS_calibration(NI,recordingDuration)
MinVAS=min(calibrateVAS);
MaxVAS=max(calibrateVAS);
disp('Is the VAS initialized correctly?')

% initialize TCS
COMport = 'COM3';
TCS=USB_TCSII_initialize(COMport);

print_to_serial(TCS,'Y0000',0);
print_to_serial(TCS,'Ue11111',0);
print_to_serial(TCS,'Ose',0); % 'TCSII-A: 'Os' (until update), 'TCSII-B/C: 'Ose'

%% set  additional variables

rating_expectation_low_low = [];
rating_expectation_high_high = [];
rating_expectation_med_high = [];
rating_expectation_med_low = [];

rating_perception_low_low = [];
rating_perception_high_high = [];
rating_perception_med_high = [];
rating_perception_med_low = [];

painful_low_low = [];
painful_high_high = [];
painful_med_high = [];
painful_med_low = [];

disp('Updated variables');
%% cue presentation

pos_ori = [-1679 -179 1680 987];
pos_zelda = [1940 -170 1621 978]; 
pos = pos_zelda;

%open cue on 2nd screen
figL= openfig('lowStim.fig', 'reuse'); %finds file with figure
set(figL, 'ToolBar', 'none');            %turns off ToolBar and MenuBar
set(figL, 'MenuBar', 'none');
set(figL,'Position', pos);
%get(gcf, 'Position')
disp('Press ENTER to continue to next cue');
pause(); 

%open cue on 2nd screen
figH= openfig('highStim.fig', 'reuse');   %finds file with figure
set(figH, 'ToolBar', 'none');               %turns off ToolBar and MenuBar
set(figH, 'MenuBar', 'none');
set(figH,'Position', pos); %figure position on screen

%% define TCS stimulation protocol
% temperatures based on pilot staircase
    
t_base=350;    %baseline temperature
t_low=440 ;    %target temp low 
t_med=470 ;    %target temp medium
t_high=500;    %target temp high 

np=10;      %number of cycles per trial
p=5;        %cycle duration
nblock=5;   %number of stimulation blocks 

CP1= periodicStim_TCSII(t_base,t_low,np,p);     % assembling the head and periods strings for temperature profile (low temp)
CP2= periodicStim_TCSII(t_base,t_med,np,p);     % medium temp
CP3= periodicStim_TCSII(t_base,t_high,np,p);    % high temp

disp('Updated temperature commands');  

%% setup of randomization of trials
% switch between matched high and low stimulus intensity condition with
% correct cue (condition LL (1) and HH (2)) and unmatched medium stimulus intensity with either
% low or high cue (condition ML (3) and MH (4)). 

recordingDuration=np*p;
            
 %creates matrix for the 8 different trials (=run) in each block based
 % on Atlas 2010. conditions: 1= low t - low cue (LL); 2= high t - high cue (HH);  
 % 3= medium t - low cue (ML); ,4= medium t - high cue (MH); 

block1 = [1 1 2 2 ];                        %First trial has to be LL or HH (reduced # to save time)
rest_runs=[ 1 1 2 2 3 3 4 4 ];              %Remaining trials in each block are randomized across all conditions
block1= block1(randperm(length(block1)));   %randomizes the first block
block1= [block1, 0 0 0 0];                  %reduced trials for conditioning phase, needs zeros to create vector with correct length

block2= randperm(length(1:2));              %first two stimuli of block 2 need to be either LL or HH
block2_rest = Shuffle([ 1 2 3 3 4 4 ],2);   %rest of block 2 
block2= cat(2,block2, block2_rest);

condition_all= repmat(rest_runs,3,1);       %equals one block of stimuli using all condition equally often                   
condition_all = Shuffle(condition_all, 2);  %randomizes every line
condition_all = [block1; block2; condition_all]; %puts everything together for final matrix
%% Experiment Loop
      
 for n= 1:nblock % 5 blocks, 1st block is conditioning

  if n >= 2       
     disp('Well done, you finished one block');
     disp('Take a break, press ENTER to continue');
     pause();
  end

    for m = 1:size(condition_all,2) %takes number of columns for trials (=8)


        if condition_all(n,m) == 1

                %set stimulation properties (for temp)
                CP = CP1; %sets stimulation temperature to "low" 
                print_to_serial(TCS,CP,0);

                %open cue on 2nd screen
                figL= openfig('lowStim.fig', 'reuse');   %finds file with figure
                set(figL, 'ToolBar', 'none');            %turns off ToolBar and MenuBar
                set(figL, 'MenuBar', 'none');
                %set (gcf,'Position', [-1679 -171 1680 987]);
                set (gcf,'Position', pos); %need to see whether this works instead of the numbers

                %get expectation rating after cue only
                disp('press ENTER to record rating of expected intensity (VAS)');
                pause();
                rating_expectation_low_low(:,end+1) = NI.inputSingleScan;
                               
                %heat stimulation with simultaneous continuous VAS rating
                disp('ready, press any key to stimulate (TCS)');
                pause()  ;
                disp('stimulating');
               
                [data,time,temp]=TCSII_launch_NI(TCS,NI,recordingDuration,0,0,1);  %[data,time,temp]=TCSII_launch_NI(TCS,NI,recording_duration,foreperiod,postperiod,feedback_duration)
                %[data] probably not necessary since we are not
                %collection VAS data during the stimulation anymore
                print_to_serial(TCS,'N350',0);       %sets TCS temperature back to baseline
                beep();
                
                disp('How intense did you perceive the stimulation overall?');
                pause();
                rating_perception_low_low(end+1) = NI.inputSingleScan;
                
                painful_low_low(end+1) = input('Did you perceive this stimulation as painful? (Yes = 1, No = 0)');
                
                save (filename); %saving everything after each stimulus to make sure we can't lose data

        elseif condition_all(n,m) == 2

                CP = CP3; %sets stimulation temperature to "high" 
                print_to_serial(TCS,CP,0);

                figH= openfig('highStim.fig', 'reuse');   
                set(figH, 'ToolBar', 'none');               
                set(figH, 'MenuBar', 'none');
                set (gcf,'Position', pos);
               
                disp('press ENTER to record rating of expected intensity (VAS)')
                pause ();
                rating_expectation_high_high(end+1) = NI.inputSingleScan;

                disp('ready, press any key to stimulate (TCS)');
                pause();
                disp('stimulating');

                [data,time,temp]=TCSII_launch_NI(TCS,NI,recordingDuration,0,0,1); 
                print_to_serial(TCS,'N350',0);
                beep();
                
                disp('How intense did you perceive the stimulation overall?');
                pause();
                rating_perception_high_high(end+1) = NI.inputSingleScan;
                
                painful_high_high(end+1) = input('Did you perceive this stimulation as painful? (Yes = 1, No = 0)');
                
                save (filename);
               

        elseif condition_all(n,m) == 3

                CP = CP2;   %sets stimulation temperature to "medium" 
                print_to_serial(TCS,CP,0);
                %open cue on 2nd screen
                figL= openfig('lowStim.fig', 'reuse'); 
                set(figL, 'ToolBar', 'none');           
                set(figL, 'MenuBar', 'none');
                set (gcf,'Position',  pos);

                disp('press ENTER to record rating of expected intensity (VAS)');
                pause ();
                rating_expectation_med_low(end+1) = NI.inputSingleScan;

                disp('ready, press any key to stimulate (TCS)');
                pause()  ;
                disp('stimulating');

                [data,time,temp]=TCSII_launch_NI(TCS,NI,recordingDuration,0,0,1);  
                print_to_serial(TCS,'N350',0);
                beep(); 
                
                disp('How intense did you perceive the stimulation overall?');
                pause();
                rating_perception_med_low(end+1) = NI.inputSingleScan;
                
                painful_med_low(end+1) = input('Did you perceive this stimulation as painful? (Yes = 1, No = 0)');
               
                save (filename);

        elseif condition_all(n,m) == 4

                CP = CP2; %sets stimulation temperature to "medium" 
                print_to_serial(TCS,CP,0);

                %open cue on 2nd screen
                figH= openfig('highStim.fig', 'visible'); 
                set(figH, 'ToolBar', 'none');           
                set(figH, 'MenuBar', 'none');
                set (gcf,'Position', pos);

                disp('press ENTER to record rating of expected intensity (VAS)');
                pause ();
                rating_expectation_med_high(end+1) = NI.inputSingleScan;

                disp('ready, press any key to stimulate (TCS)');
                pause();  
                disp('stimulating');
                [data,time,temp]=TCSII_launch_NI(TCS,NI,recordingDuration,0,0,1);  
                print_to_serial(TCS,'N350',0);
                beep(); 
                
                disp('How intense did you perceive the stimulation overall?');
                pause();
                rating_perception_med_high(end+1) = NI.inputSingleScan;
                
                painful_med_high(end+1) = input('Did you perceive this stimulation as painful? (Yes = 1, No = 0)');
              
                
                save (filename);
                
        elseif condition_all(n,m) == 0
                disp('Skip to the next trial');
        
        else
             disp ('ERROR');
        end
    end
 end
 
save (filename);

%% FIGURES 
%creates figures of ratings for each condition (all 6 trials)

figure
plot(time,rating_cont_low_low)
title('Continuous rating: low cue - low stim')
xlabel('time [s]')
ylabel('VAS rating [V]')
savefig([subject_string ' ' 'LL .fig']);

figure
plot(time,rating_cont_high_high) 
title('Continuous rating: high cue - high stim')
xlabel('time [s]')
ylabel('VAS rating [V]')
savefig([subject_string ' ' 'HH .fig']);


figure
plot(time,rating_cont_med_low)
title('Continuous rating: low cue - medium stim')
xlabel('time [s]')
ylabel('VAS rating [V]')
savefig([subject_string ' ' 'LM .fig']);


figure
plot(time,rating_cont_med_high)
title('Continuous rating: high cue - medium stim')
xlabel('time [s]')
ylabel('VAS rating [V]')
savefig([subject_string ' ' 'HM .fig']);

